# -*- coding: utf-8 -*-
import requests
import json
from urllib import parse
from django.shortcuts import render,redirect
from django.http import JsonResponse
from django.http import HttpResponse
from django.views.decorators import csrf
import sys
import mysql.connector
from . import getsql
from myapp.models import User

def login(request):
    context={}
    if request.POST:
        user=request.POST['user']
        password=request.POST['password']
        word=User.objects.get(account=user).password
        if password==word:
            context['message'] = '登陆成功！'
            context['user'] =user
            request.session['imglink']=User.objects.get(account=user).headimg
            request.session['uid']=User.objects.get(account=user).id
            request.session['user']=user
            # flag=render(request,'welcome.html',context)
            # flag.set_signed_cookie('password',password,salt='liuxu')
            return redirect('/')
        else:
            context['message'] = '登陆失败！'
            context['user'] = user
            return render(request, 'welcome.html', context)
    else:
        context['message'] = '或登录!'
        context['user'] = '请注册'
        return render(request, 'login.html',context)
def register(request):
    if request.POST:
        context={}
        user=request.POST['user']
        password1=request.POST['password1']
        password2=request.POST['password2']
        if password1==password2:
            add=User(account=user,password=password1)
            try:
                add.save()
                request.session['imglink'] = User.objects.get(account=user).headimg
                request.session['user'] = user
                context['message'] = '注册成功！'
                context['user'] =user
                return render(request,'welcome.html',context)
            except:
                context['message'] = '注册失败！'
                context['user'] =user
                return render(request, 'welcome.html', context)
        else:
            context['message'] = '注册失败,两次输入的密码不一致！'
            context['user'] = user
            return render(request, 'welcome.html', context)
    else:
        return render(request, 'register.html')

def info(request):
    user = request.session.get('user', 'False')
    imglink=request.session.get('imglink', '/static/images/nobody.jpg')
    context={'user':user,'imglink':imglink}
    return JsonResponse(context)

def status(request):
    user = request.session.get('user', 'False')
    imglink=request.session.get('imglink', '/static/images/nobody.jpg')
    uid=request.session.get('uid', '不存在')
    context={'user':user,'imglink':imglink,'uid':uid}
    return JsonResponse(context)

def loginout(request):
    request.session.flush()
    return redirect('/')






